﻿@using RatScanner.ViewModel
@inject SettingsVM SettingsVM
@inject NavigationManager NavigationManager
@inject IJSRuntime JSRuntime;
@implements IDisposable

<MudGrid Class="px-2 my-2" Spacing="0" Style="position: fixed; bottom: 0">
    <MudItem xs="6" Class="d-flex justify-start pr-1">
        <MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" Class="light-green darken-3" FullWidth="true" OnClick="SaveSettings">Save</MudButton>
    </MudItem>
    <MudItem xs="6" Class="d-flex justify-end pl-1">
        <MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Delete" Color="Color.Error" FullWidth="true" OnClick="DiscardSettings">Cancel</MudButton>
    </MudItem>
</MudGrid>

<MudOverlay @bind-Visible="_showSpinner" Absolute="true" DarkBackground ZIndex="9999">
    <MudProgressCircular Color="Color.Primary" Size="Size.Large" Indeterminate="true" />
</MudOverlay>

@code {
    private bool _showSpinner;

    private async void SaveSettings() {
        _showSpinner = true;
        await SettingsVM.SaveSettings();
        StateHasChanged();
        NavigationManager.NavigateTo("/app");
    }

    private void DiscardSettings() {
        SettingsVM.LoadSettings();
        StateHasChanged();
        NavigationManager.NavigateTo("/app");
    }

    protected override void OnInitialized() {
        SettingsVM.PropertyChanged += PropertyChangeHandler;
    }

    private async void PropertyChangeHandler(object? sender, EventArgs e) {
        await InvokeAsync(() => StateHasChanged());
    }

    public void Dispose() {
        SettingsVM.PropertyChanged -= PropertyChangeHandler;
    }

}
